from Crypto.Hash import SHA256
from Crypto.PublicKey import ECC
from Crypto.Signature import DSS
from Crypto.Util.asn1 import DerSequence


def sign(data):  # 输入为string或byte
    if type(data) == str:
        data = data.encode()
    private_key = ECC.generate(curve='P-256')
    public_key = private_key.public_key()
    h = SHA256.new(data)
    signer = DSS.new(private_key, 'fips-186-3', encoding='der')
    signature = signer.sign(h)
    der = DerSequence()
    r = der.decode(signature)[0]
    s = der.decode(signature)[1]
    vrs = [27 + (r % 2), r, s]
    return vrs, public_key


def authenticate(hash,public_key,signature):
    verifier = DSS.new(public_key, 'fips-186-3', encoding='der')
    try:
        verifier.verify(hash, signature)
        return True
    except ValueError:
        return False
